﻿using CPPEI.ETL.DataServiceInterface;
using CPPEI.WebApi;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using ENT = CPPEI.ETL.Domain.Entities;
using MOD = CPPEI.ETL.Domain.Models;
using SER = CPPEI.ETL.Domain.Services;

namespace CPPEI.ETL.WebApi
{
    /// <summary>
    /// 手动执行任务
    /// </summary>
    [CPPEI.WebApi.PostAction("ETL", "ManualExecuteTask", "1.0")]
    public class ManualExecuteTaskAction : BaseAction<ManualExecuteTaskParams, ManualExecuteTaskResult>
    {
        protected override ActionResult<ManualExecuteTaskResult> OnExecute(ActionContext context, 
            SysParameters sysParameters,
            ManualExecuteTaskParams opParams)
        {
            Logger.DebugToTag(Library.LogTAG, string.Format("ManualExecuteTaskAction,TaskId:{0}", opParams.TaskId));

            SER.TaskService service = new SER.TaskService();

            List<string> tempFiles = new List<string>();

            Dictionary<string, string> parameterDict = new Dictionary<string, string>();
            foreach (string key in context.HttpRequest.Form.Keys)
            {
                if(key.StartsWith("tp:"))
                {
                    parameterDict.Add(key.Replace("tp:", string.Empty), context.HttpRequest.Form[key]);
                }
            }

            foreach (string  fileKey in context.HttpRequest.Files.AllKeys)
            {
                if (fileKey.StartsWith("tp:"))
                {
                    HttpPostedFile httpPostedFile = context.HttpRequest.Files[fileKey];
                    string filePath = string.Format("{0}{1}.{2}", CPPEI.ETL.Domain.Configs.UploadFileDirectory, Guid.NewGuid(), GetExtension(httpPostedFile.FileName));

                    FileInfo fileInfo = new FileInfo(filePath);
                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }

                    httpPostedFile.SaveAs(filePath);
                    tempFiles.Add(filePath);
                    parameterDict.Add(fileKey.Replace("tp:", string.Empty), filePath);
                }
            }

            ServiceResult<MOD.ManualExecuteResult> serResult = service.ManualExecute(context.UserId, opParams.TaskId, parameterDict);

            for (int index = 0; index < tempFiles.Count; index++)
            {
                try
                {
                    File.Delete(tempFiles[index]);
                }
                catch(Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("删除文件:{0}出错,ex:{1}", tempFiles[index], ex));
                }
            }

            if (serResult.IsSuccess)
            {
                ManualExecuteTaskResult result = new ManualExecuteTaskResult();
                result.NeedDataVerification = serResult.Data.NeedDataVerification;
                result.BatchId = serResult.Data.BatchId;
                result.TaskId = serResult.Data.BatchId;
                result.CodeConvertFailureCount = serResult.Data.CodeConvertFailureCount;
                result.DataVerifyFailureCount = serResult.Data.DataVerifyFailureCount;
                result.DataCount = serResult.Data.DataCount;
                result.InsertFailureCount = serResult.Data.InsertFailureCount;
                result.InsertSuccessCount = serResult.Data.InsertSuccessCount;
                result.TypeVerifyFailureCount = serResult.Data.TypeVerifyFailureCount;

                return new ActionResult<ManualExecuteTaskResult>(result);
            }
            else
            {
                return new ActionResult<ManualExecuteTaskResult>(serResult.IsSuccess, serResult.ErrorCode, serResult.Message, null);
            }
        }

        private string GetExtension(string fileName)
        {
            string[] segments = fileName.Split(new char[] { '.' });
            if (segments.Length > 0)
            {
                return segments.Last();
            }
            return fileName;
        }
    }

    public class ManualExecuteTaskParams
    {
        [Parameter]
        public Guid TaskId { get; set; }
    }

    public class ManualExecuteTaskResult
    {
        /// <summary>
        /// 需要数据审核
        /// </summary>
        public bool NeedDataVerification { get; set; }

        /// <summary>
        /// 批次id
        /// </summary>
        public Guid BatchId { get; set; }
        public Guid TaskId { get; set; }

        public long DataCount { get; set; }

        public long TypeVerifyFailureCount { get; set; }

        public long DataVerifyFailureCount { get; set; }

        public long CodeConvertFailureCount { get; set; }

        public long InsertSuccessCount { get; set; }

        public long InsertFailureCount { get; set; }
    }
}
